package com.walkline.util;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.global.Formatter;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import localization.RedFlowerResource;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.CDMAInfo;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Clipboard;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.GPRSInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.system.SIMCardInfo;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;

public class Functions implements RedFlowerResource
{
	private static ResourceBundle _resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	//private static PurchaseHistoryListingListener purchaseHistoryListingListener;
	//private static PaymentEngine engine = PaymentEngine.getInstance();

	/**
	 * 把字节大小转换为KB、MB和GB，带小数位
	 * @param size 需要转换的字节大小
	 * @param decimal 小数点后保留的位数
	 * @return 返回一个合适的字符串以显示文件大小
	 */
    public static String formatSize(double size, int decimal)
    {
    	long SIZE_KB = 1024;
    	long SIZE_MB = SIZE_KB * 1024;
    	long SIZE_GB = SIZE_MB * 1024;

    	if (size < SIZE_KB) {
    		return size + " B";
    	} else if(size < SIZE_MB) {
    		return new Formatter("en").formatNumber(size/SIZE_KB, decimal) + " KB";
    	} else if(size < SIZE_GB) {
    		return new Formatter("en").formatNumber(size/SIZE_MB, decimal) + " MB";
    	} else {
    		return new Formatter("en").formatNumber(size/SIZE_GB, decimal) + " GB";
    	}
    }

    /**
     * 在数组中查找指定数值的，并返回序号
     * @param array String数组
     * @param key 指定的数值
     * @return 返回指定数值所在的序号
     */
    public static int findInArray(String[] array, int key)
    {
    	int i;
    	
    	for (i=0; i<array.length; i++)
    	{
    		if(Integer.valueOf(array[i]).intValue()==key) {break;}
    	}

    	return (i == array.length) ? -1 : i;
    	//if (i == array.length)
    	//{
    	//	return -1;
    	//} else{
    	//	return i;
    	//}
    }
    
    /**
     * 为了美观对齐而产生的多余函数
     * @param id 字符串形式的数值
     * @return 返回格式化后的字符串
     */
	public static String formatID(String id)
	{
		String newString = "";
		String spaceString = "  ";
		int idLength = id.length();
		
		if(idLength >= 3)
		{
			newString = id;
		} else {
			for(int i=0; i<3-idLength; i++)
			{
				spaceString += Characters.SPACE ;
			}
			newString = spaceString + id;
		}

		return newString;
	}

	/**
	 * 获取电池电压信息，并返回格式化后的数值
	 * @return 返回以V为单位小数点后保留1位的电压数值
	 */
	public static String getVolt()
	{
		double volt=DeviceInfo.getBatteryVoltage();

		return new Formatter("en").formatNumber(volt/1000, 1);
	}

	/**
	 * 获取指定存储设备上的空间信息
	 * @param storeType 存储类型，包括机身内置（"store/"）和外置媒体卡（"SDCard/"）
	 * @return 返回指定格式的存储空间信息
	 */
	public static String getStorageInfo(String storeType)
    {
    	FileConnection _fileConnection;
        String root = null;
        String retString = null;
        Enumeration enumRoots = FileSystemRegistry.listRoots();

        while (enumRoots.hasMoreElements())
        {
            root = (String) enumRoots.nextElement();
            if (root.equalsIgnoreCase(storeType))
            {
                try {
					_fileConnection = (FileConnection) Connector.open("file:///" + root.toString());

			        long _totalSpace = _fileConnection.totalSize();
			        //long _usedSpace=_fileConnection.usedSize();
			        long _freeSpace = _fileConnection.availableSize();

			        retString = Functions.formatSize(_totalSpace, 1) + " (" + Functions.formatSize(_freeSpace, 1) + " free)";
				} catch (Exception e) {}
            }
        }            	

        if (retString == null) {retString = getResString(STORAGE_INFORMATION_NONE);}
        return retString;
    }

    /**
     * 获取机器支持的所有视频编码类型表
     * @return 返回数组形式的类型表
     */
    public static String[] getVideoEncodings()
    {
        String encodingsString = System.getProperty("video.encodings");
        
        if( encodingsString == null ) {return null;}

        Vector encodings = new Vector();       
        int start = 0;
        int space = encodingsString.indexOf(' ');

        while (space != -1)
        {
            encodings.addElement(encodingsString.substring(start, space));          
            start = space + 1;
            space = encodingsString.indexOf(' ', start);
        }        
        encodings.addElement(encodingsString.substring(start, encodingsString.length())); 
        
        String[] encodingArray = new String[encodings.size()];
        encodings.copyInto(encodingArray);
        
        return encodingArray;
    }

	/**
	 * 获取手机卡IMSI号码序列
	 * @return 返回该序列
	 */
    private static String getIMSI()
    {
    	String imsi = "";

    	try {
			if (RadioInfo.getNetworkType()==RadioInfo.NETWORK_CDMA) {
				return GPRSInfo.imeiToString(CDMAInfo.getIMSI());
			} else {
				//imsi=replaceString(GPRSInfo.imeiToString(SIMCardInfo.getIMSI()),".","");
				imsi = GPRSInfo.imeiToString(SIMCardInfo.getIMSI());

				return imsi;
			}
		} catch (Exception e) {}

    	return null;
    }
    
    /**
     * 调用对话框显示手机卡IMSI码，并复制到剪贴板
     */
    public static void showIMSI()
    {
		String[] choices = getResStringArray(DIALOG_CHOICE_OKCOPY);
		String imsi = getIMSI();

		if (imsi != null)
		{
			Dialog imsiDialog = new Dialog(getResString(DIALOG_MESSAGE_IMSI_CODE) + imsi, choices, null, 1, Bitmap.getPredefinedBitmap(Bitmap.INFORMATION));

			imsiDialog.doModal();
			if (imsiDialog.getSelectedValue() == 1)
			{
				Clipboard cb=Clipboard.getClipboard();
				cb.put(new String(imsi));
			}
		}else {
			Dialog.alert(getResString(MESSAGE_ERROR_NO_SIM));
		}
    }

    public static String getResString(int key) {return _resources.getString(key);}

    public static String[] getResStringArray(int key) {return _resources.getStringArray(key);}

    public static void errorDialog(final String message)
    {
        UiApplication.getUiApplication().invokeAndWait(new Runnable()
        {
            public void run() {Dialog.alert(message);} 
        });
    }
}